<template>
  <li :class="{ completed: item.done, editing: isEditing }">
    <div class="view">
      <input class="toggle" type="checkbox" :checked="item.done" @change="handlerChangeInput(item)" />
      <label @dblclick="handlerDblCllick">{{ item.name }}</label>
      <button class="destroy" @click="delTodo(item.id)"></button>
    </div>
    <input class="edit" v-model="currentName" ref="inputRef" @blur="handlerBlur" @keyup="e => handlerKeyup(e)" />
  </li>
</template>

<script setup lang="ts">
import { nextTick, ref } from 'vue'
import useStore from '../store'
import { ITodoItem } from '../types/data'

const props = defineProps<{
  item: ITodoItem
}>()

const isEditing = ref<boolean>(false)
const inputRef = ref<HTMLInputElement>()
const currentName = ref()

const { main } = useStore()
const { delTodo, updateTodo } = main

function handlerChangeInput(item: ITodoItem) {
  updateTodo(item.id, 'done', !item.done)
}

function handlerDblCllick() {
  isEditing.value = true
  nextTick(() => {
    inputRef.value?.focus()
  })
  currentName.value = props.item.name
}

function handlerBlur() {
  isEditing.value = false
  currentName.value = ''
}

function handlerKeyup(e: KeyboardEvent) {
  if (e.key === 'Escape') {
    handlerBlur()
    return
  }
  if (e.key === 'Enter') {
    if (currentName.value.trim() === '') {
      return alert('任务名不能为空!')
    }
    updateTodo(props.item.id, 'name', currentName.value)
    handlerBlur()
  }
  
}
</script>

<style scoped lang="less">

</style>
